package org.glorylight.hacks.maps.bean;

import java.io.Serializable;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.inject.Named;

import org.primefaces.event.map.MarkerDragEvent;
import org.primefaces.event.map.PointSelectEvent;
import org.primefaces.model.map.DefaultMapModel;
import org.primefaces.model.map.LatLng;
import org.primefaces.model.map.MapModel;
import org.primefaces.model.map.Marker;
import org.springframework.context.annotation.Scope;


@Named
@Scope("session")
public class LocationBean implements Serializable {

	private static final long serialVersionUID = 6133894884069685875L;
	private MapModel jakartaMap = new DefaultMapModel();
	private double latitute;
	private double longitute;
	private Marker currentPos = null;

	public void onPointSelect(PointSelectEvent event) {
		LatLng latlng = event.getLatLng();
		this.latitute = latlng.getLat();
		this.longitute = latlng.getLng();
		if(getCurrentPos() == null) {
			setCurrentPos(new Marker(new LatLng(latitute, longitute), "aku disini"));
			getCurrentPos().setDraggable(true);
		}
		jakartaMap.addOverlay(getCurrentPos());
		addMessage(new FacesMessage(FacesMessage.SEVERITY_INFO, "Marker Added", "Lat:" + latitute + ", Lng:" + longitute));
	}
	
	public void addMessage(FacesMessage message) {
		FacesContext.getCurrentInstance().addMessage(null, message);
	}
	
	public MapModel getNowhere() {
		return jakartaMap;
	}
	
	public double getLatitute() {
		return latitute;
	}
	
	public double getLongitute() {
		return longitute;
	}
	
	public String getCenterPosition() {
		return ""+latitute+", "+longitute;
	}
	
	public Marker getCurrentPos() {
		return currentPos;
	}

	public void setCurrentPos(Marker currentPos) {
		this.currentPos = currentPos;
	}

	public void onMarkerDrag(MarkerDragEvent event) {
		setCurrentPos(event.getMarker());
		getCurrentPos().setDraggable(true);
	}
	
	public void addMarker(ActionEvent actionEvent) {
		Marker marker = new Marker(new LatLng(latitute, longitute), "aku disini");
		jakartaMap.addOverlay(marker);
		addMessage(new FacesMessage(FacesMessage.SEVERITY_INFO, "Marker Added", "Lat:" + latitute + ", Lng:" + longitute));
	}
}
